import React, { useState, useEffect } from 'react';
import { Image, View, Input } from '@tarojs/components';
import { connect } from 'react-redux';
import utils from '@/utils/index';
import pSearch from '@/images/common/searchIcon.png';
import pClear from '@/images/common/searchClose.png';
import './index.scss';

const Search = ({
  dispatch,
  className = '',
  historySelected = '',
  handleStatus = null,
  placeholder = '输入关键词',
}) => {
  const [searchValue, setSearchValue] = useState('');
  const [focus, setFocus] = useState(false);

  useEffect(() => {
    setSearchValue(historySelected);
    historySelected.length > 0 && handleSearch(historySelected);
  }, [historySelected]);

  const inputHandler = (e) => {
    setSearchValue(e.detail.value);
  };

  const handleSearch = (value) => {
    dispatch({
      type: 'otherApi/customerServiceSearch',
      payload: { alias: 'helpCenter', name: value },
    });
    let curSearchHistory = utils.getLocalStorage('searchHistory');
    if (curSearchHistory) {
      let idx = curSearchHistory.indexOf(value);
      idx >= 0 && curSearchHistory.splice(idx, 1);
      curSearchHistory.unshift(value);
    } else {
      curSearchHistory = [value];
    }
    utils.setLocalStorage('searchHistory', curSearchHistory);
    handleStatus(3);
  };

  const handleClear = () => {
    setSearchValue('');
  };

  return (
    <View className={['flex-row-center-center', 'searchService', className].join(' ')}>
      <View className="searchBox">
        <Image className="searchIcon" src={pSearch} />
        <Input
          className="searchInput"
          type="text"
          confirmType="search"
          placeholder={placeholder}
          placeholderClass="inputPlaceholder"
          maxLength={15}
          value={searchValue}
          focus={focus}
          onFocus={() => {
            setFocus(true);
            handleStatus(2);
          }}
          onBlur={() => {
            setFocus(false);
            handleStatus('back');
          }}
          onConfirm={() => {
            handleSearch(searchValue);
          }}
          onInput={(e) => {
            inputHandler(e);
          }}
        />
        <View className="flex-row-center-center clear" onClick={handleClear}>
          {searchValue.length > 0 && <Image className="img" src={pClear} />}
        </View>
        <View
          className="flex-row-center-center btn customePageStyleBg20 customePageStyle"
          onClick={() => handleSearch(searchValue)}
        >
          搜索
        </View>
      </View>
    </View>
  );
};

export default connect(({}) => ({}))(Search);
